package com.example.maple.ccsclient.presenter;

import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.Nullable;

import com.example.maple.ccsclient.interfaces.ISettingView;

import java.io.File;

/**
 * Created by maple on 2016/7/6.
 */
public class SettingPresenter {

	int fileLength;

	ClearCacheAsyncTask mTask;
	private Context mContext;

	ISettingView mISettingView;

	public SettingPresenter(ISettingView iSettingView, Context context) {
		mContext = context;
		mISettingView = iSettingView;
	}


	public void clearCache() {
		File folder = new File("/sdcard/集字系统/");
		if (!folder.exists() && !folder.isDirectory()) {
			return ;
		}
		fileLength = folder.list().length - 1;
		//设置进度条最大值
		mISettingView.setProgressBarValue(fileLength);

		mTask = new ClearCacheAsyncTask();
		mTask.execute();

	}

	//取消任务
	public void cancelTask(){
		if(null != mTask && !mTask.isCancelled()){
			mTask.cancel(false);
		}
	}

	public class ClearCacheAsyncTask extends AsyncTask<Nullable, Integer, String> {

		@Override
		protected String doInBackground(Nullable... params) {


			File folder = new File("/sdcard/集字系统/");
			if (!folder.exists() && !folder.isDirectory()) {
				return "缓存文件不存在";
			} else if (folder.isDirectory()) {

				String[] fileList = folder.list();
				for (int i = 0; i < fileList.length; i++) {
					File readFile = new File("/sdcard/集字系统/" + fileList[i]);
					if (!readFile.isDirectory()) {
						//开始清除缓存
						readFile.delete();
						publishProgress(i);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}

				}

				return "清除完成";
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mISettingView.updateProgressBar(values[0]);
			mISettingView.showClearFile(String.format("%s/%s",values[0],fileLength));
		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			mISettingView.hiddenCache();
			mISettingView.showDialog(s);
		}
	}
}
